package com.teamin.web.controller;

import com.teamin.config.ErrorCode;
import com.teamin.config.OSSUtil;
import com.teamin.dto.NetDiskShareDTO;
import com.teamin.entity.NetDisk;
import com.teamin.entity.NetDiskShare;
import com.teamin.service.INetDiskService;
import com.teamin.service.UserService;
import com.teamin.web.exception.GlobalErrorInfoException;
import com.teamin.web.model.ErrorInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Api(description = "网盘api-2",tags = "网盘")
@RestController
@RequestMapping(value = "/circle/netdisk")
public class NetDiskController extends BaseController {

    @Autowired
    private INetDiskService netDiskService;

    @Autowired
    private UserService userService;

    @Autowired
    OSSUtil ossUtil;

    /**
     * 分享文件
     */
    @PostMapping("/file/share")
    @ApiOperation("文件分享")
    public List<NetDisk> fileShare(@RequestAttribute("loginUserId") Long loginUserId, @ApiParam(value = "圈子ID", required = true) @RequestParam Integer circleId, @ApiParam(value = "分享文件Id（多个id以逗号隔开）", required = true) @RequestParam String fileIds) throws GlobalErrorInfoException {
        // 不属于圈子
        if (!userService.userInCircle(loginUserId, Long.valueOf(circleId))) {
            throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
        }
        NetDiskShareDTO netDiskShareDTO = new NetDiskShareDTO();
        netDiskShareDTO.setCreateUserId(loginUserId);
        netDiskShareDTO.setFileIds(fileIds);
        netDiskShareDTO.setCircleId(circleId);
        NetDiskShare netDiskShare = netDiskService.createShare(netDiskShareDTO);

        List<NetDisk> netDiskList = netDiskService.findByShare(netDiskShare.getId());
        List<NetDisk> netList = new ArrayList<>();
        for (NetDisk netDisk : netDiskList) {
            if (1 == netDisk.getIsFile()) {
                try {
                    netDisk.setFileUrl(ossUtil.getUrlByKey(netDisk.getUuid()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                netList.add(netDisk);
            }
            if (0 == netDisk.getIsFile()) {
                findFile(netDisk, netList);
            }
        }
        return netList;
    }

    /**
     * 递归查询文件
     *
     * @param netDisks
     * @return
     */
    private void findFile(NetDisk netDisk, List<NetDisk> netDisks) {
        if (netDisk.getIsFile() == 0) {
            netDisk.setFileName(null);
        }
        List<NetDisk> diskList = netDiskService.findChild(netDisk);
        for (NetDisk netDiskFile : diskList) {
            if (netDiskFile.getIsFile() == 0) {
                findFile(netDiskFile, netDisks);
            }
            if (netDiskFile.getIsFile() == 1) {
                try {
                    netDisk.setFileUrl(ossUtil.getUrlByKey(netDisk.getUuid()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                netDisks.add(netDiskFile);
            }
        }
    }

    /**
     * 文件重命名
     */
    @PostMapping("/file/rename")
    @ApiOperation("重命名文件")
    public void renameFile(@RequestAttribute("loginUserId")
                               @ApiParam(hidden = true) Long loginUserId,
                           @ApiParam(value = "父目录Id", required = true) @RequestParam Long parentId,
                           @ApiParam(value = "文件/文件夹Id", required = true) @RequestParam Integer fileId,
                           @ApiParam(value = "文件/文件夹名称", required = true) @RequestParam String fileName)throws Exception {
        NetDisk netDisk = new NetDisk();
        netDisk.setId(Long.valueOf(fileId));
        netDisk.setFileName(fileName);
        netDisk.setParentId(parentId);
        netDiskService.rename(loginUserId, netDisk);
    }

    /**
     * 获取文件详情
     */
    @GetMapping("/file/details")
    @ApiOperation("获取文件详情")
    public NetDisk fileDetails(@ApiParam(value = "文件Id", required = true) @RequestParam Integer fileId) throws GlobalErrorInfoException {
        NetDisk netDisk;
        try {
            netDisk = netDiskService.fileDetails(Long.valueOf(fileId));
            if (netDisk == null) {
                throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.DATA_FAIL));
            }
        } catch (RuntimeException ex) {
            throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.DATA_FAIL));
        }
        return netDisk;
    }

    /**
     * 获取文件夹详情
     */
    @GetMapping("/folder/details")
    @ApiOperation("获取文件夹详情")
    public NetDisk folderDetails(@ApiParam(value = "文件夹Id", required = true) @RequestParam Long folderId) throws GlobalErrorInfoException {
        NetDisk netDisk;
        try {
            netDisk = netDiskService.folderDetails(folderId);
            if (netDisk == null) {
                throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.DATA_FAIL));
            }
        } catch (RuntimeException ex) {
            throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.DATA_FAIL));
        }
        return netDisk;
    }

    @PostMapping("/file/uploaded/notify")
    @ApiOperation("通知服务器文件上传成功")
    public void uploadedNotify(@ApiParam(value = "圈子Id", required = true) @RequestParam Long circleId,
                               @ApiParam(value = "文件uuid(多个以,号分割)", required = true) @RequestParam String uuids){
        List<String> uuidList = CollectionUtils.arrayToList(uuids.split(","));
        this.netDiskService.uploadSuccessHandler(uuidList);
    }
}
